package com.fcy.teamwork.widget

import androidx.viewpager2.widget.ViewPager2
import com.fcy.teamwork.R
import com.google.android.material.bottomnavigation.BottomNavigationView

/**
 * BottomNavigationView 与 ViewPager2 位置一致
 */
class MediatorForBNVWithVP2(
    private val vp2: ViewPager2,
    private val bnv: BottomNavigationView,
    private val menuIds: IntArray
) {
    private var currentPosition = 1

    inner class VP2Callback : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            if (position == currentPosition)
                return
            currentPosition = position
            bnv.selectedItemId = menuIds[position]
        }
    }

    init {
        vp2.registerOnPageChangeCallback(VP2Callback())
        bnv.setOnItemSelectedListener { it ->
            val position = when (it.itemId) {
                R.id.action_message -> 0
                R.id.action_mine -> 2
                R.id.action_taskMarket -> 1
                else -> throw IllegalStateException("不存在该menu")
            }
            if (currentPosition != position) {
                vp2.setCurrentItem(position, true)
            }
            true
        }
    }
}